package com.example.demo.manager;

import com.example.demo.domain.db.Order;
import com.example.demo.domain.solr.Orders;
import com.example.demo.manager.inf.CanalManager;
import com.example.demo.repository.OrdersUtil;
import com.example.demo.repository.SolrRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @Description
 * @Author <a href="hedong.wu@baozun.com">wuhedong</a>
 * @Date 2020/5/26 16:49
 **/
@Component("order")
@Slf4j
public class OrderManager implements CanalManager<Order> {

    @Autowired
    SolrRepository solrRepository;

    @Override
    public boolean doOnDelete(Order order) {
        solrRepository.deleteById(order.getId());
        return true;
    }

    @Override
    public boolean doOnUpdate(Order beforeOrder, Order afterOrder) {
        Optional<Orders> byId = solrRepository.findById(afterOrder.getId());
        if (!byId.isPresent()) {
            solrRepository.save(new Orders(afterOrder));
            return true;
        }
        //添加字段要修改，反射效率低  弃用
        OrdersUtil.mergeOrdersWithorder(byId.get(),afterOrder);
        solrRepository.save(byId.get());
        return true;
    }

    @Override
    public boolean doOnAdd(Order order) {
        solrRepository.save(new Orders(order));
        return true;
    }

    @Override
    public Class<Order> getHandleClass() {
        return Order.class;
    }

}
